package pri.black.dogview.handler;

import com.alibaba.fastjson.JSONObject;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import java.io.IOException;

public class AuthAccessDeniedHandler implements AccessDeniedHandler {
    private static final Logger log = LoggerFactory.getLogger(AuthAccessDeniedHandler.class);

    private static String DENIED_MSG = null;
    static {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 405);
        jsonObject.put("msg", "not permittted");
        DENIED_MSG = jsonObject.toJSONString();
    }

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        log.error("无法通过验证 {}", accessDeniedException.getMessage());
        response.setStatus(403);
        String youAreNotAllowed = DENIED_MSG;
        response.setContentLength(youAreNotAllowed.getBytes().length);
        response.setContentType("application/json");
        response.getOutputStream().print(youAreNotAllowed);
        response.getOutputStream().flush();
    }
}
